package com.kaiyidiannao.model.req.base;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.db.RpcCacheDBDao;
import com.kaiyidiannao.db.RpcCacheDBRecord;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.model.AppSignal;
import com.kaiyidiannao.model.Result;
import com.taplinker.core.util.LogUtil;
import com.taplinker.core.util.MD5Util;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public abstract class BaseCommand extends AsyncTask<Object, Object, Result> implements Command {

    //onPreExecute()进行判断是否联网前表示：上次检测是否联网，判断联网后表示：当前是否联网
    private static boolean lastIsConnected = true;
    boolean isConnected = HttpUtils.isConnected();
    //先判断当前网络状态和上一次读取的是否相同，不同则提示
    @Override
    protected void onPreExecute() {
//        SharedPreferences sp = DataCenter.context.getSharedPreferences(DataCenter.LOGIN_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
//        // SessionId
//        if (DataCenter.context != null) {
//            RpcClientContext.getInstance().setCookies("PHPSESSID=" + sp.getString(LoginActivity.SESSION_ID, ""));
//            // ImagePath
//            if (TextUtils.isEmpty(DataCenter.pictureServerBasePath)) {
//                DataCenter.pictureServerBasePath = sp.getString(LoginActivity.SERVER_BASE_PATH,"");
//            }
//        }



        if(lastIsConnected != isConnected) {
            if(isConnected) {
                Toast.makeText(DataCenter.context, "网络已恢复", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(DataCenter.context, "无法连接到网络，进入离线模式", Toast.LENGTH_SHORT).show();
            }
        }
        lastIsConnected = isConnected;
        super.onPreExecute();
    }

    //在后台线程做的：
    //如果联网则调用go()发送请求，调用postGo()缓存到数据库；
    //如果断网则调用stay()从数据库里取，取到的数据包装成Result，其中result.status为AppSignal.OK
    @Override
    protected Result doInBackground(Object... params) {
        if(lastIsConnected){
            Result result = go(getRequestUrl(), getRequestParamters());
            String p = "";
            try {
                p = getRequestParamters().toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            LogUtil.d("RPC_doInBackground()", "url:" + getRequestUrl() + "; paramters:" + p);
            if(result != null && result.status == AppSignal.OK) {
                postGo(result);
            }
            return result;
        } else {
            return stay();
        }
    }

    //在主线程调用，doInBackground()返回结果后执行
    @Override
    protected void onPostExecute(Result result) {

        if(result != null){
            super.onPostExecute(result);
            if (result.status == AppSignal.OK  &&  result.object != null) {
                Log.d("HttpTemplate", "-resultStr-" + result.object.toString());
                yes(result);
            } else {
                no(result);
            }
        } else {
            no(null);
        }
    }

    @Override
    public Result stay() { //断网时后台执行，取本地数据库
        LogUtil.d("RPC_stay()", "Loading..........................");
        Result result = new Result();
        RpcCacheDBRecord record = null;
        if(!TextUtils.isEmpty(getkey())) {
            record = RpcCacheDBDao.getInstance().doQuery(getkey());
        }
        if(record != null) {
            result.status = AppSignal.OK;
            result.object = record.getBody();
        } else {
            result.status = AppSignal.NO_NETWORK;
            result.object = "";
        }
        return result;
    }

    @Override
    public void postGo(Result result) { // go()之后执行，存到本地数据库
    	if(result != null && result.status == AppSignal.OK && !TextUtils.isEmpty(getkey())) {
    		RpcCacheDBDao.getInstance().doUpdate(new RpcCacheDBRecord(getkey(), (String) result.object));
    	}
    };

    @Override
    public void yes(Result result) {
        try {
            JSONObject jsonObject = new JSONObject(result.object.toString());
            DataCenter.code = jsonObject.optString("code");
            DataCenter.msg = jsonObject.optString("msg");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出错误码和错误信息，可在各req model的no()中调用
     */
    @Override
    public void no(Result result) {
        Log.d(DataCenter.LOG_INFO, "BaseCommand.no(),Result.status=" + result.status);

        if(!HttpUtils.isConnected() || result.status == AppSignal.NO_NETWORK) {
            Toast.makeText(DataCenter.context, "网络连接错误，请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        } else if (result.status == AppSignal.RPC_TIMEOUT) {
            Toast.makeText(DataCenter.context, "网络不给力，请稍候重试", Toast.LENGTH_SHORT).show();//请求数据超时，请重试
            return;
        } else if (result.status == AppSignal.SC_NOT_FOUND) {
            Toast.makeText(DataCenter.context, "服务器离家出走了,请检查服务器请求地址", Toast.LENGTH_LONG).show();
            return;
        } else if (result.status == AppSignal.HTTP_ERROR) {
            Toast.makeText(DataCenter.context, "网络请求失败，请稍候重试", Toast.LENGTH_LONG).show();
            return;
        } else if (result.status == AppSignal.SERVER_ERROR) {
            Toast.makeText(DataCenter.context, "服务器异常，请稍候重试", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if(!isConnected){

            }else {
                Log.d(DataCenter.LOG_ERROR, "BaseCommand.no(): result null");
                Toast.makeText(DataCenter.context, "网络不给力，请稍候重试", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    private String getkey() {
        if(TextUtils.isEmpty(getRequestUrl())) {
            return null;
        }
        StringBuffer sb = new StringBuffer("");
        sb.append(getRequestUrl());
        HashMap<String, String> paramters = getRequestParamters();
        if(paramters != null && paramters.size() > 0) {
            for(String k : paramters.keySet()) {
                sb.append(k).append(paramters.get(k));
            }
            sb.append(DataCenter.userBean.getUsername());
            sb.append(DataCenter.userBean.getUserid());
        }
        return MD5Util.getMD5String(sb.toString());
    }

}